<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="商品名称">
          <el-input 
            v-model="queryParams.goodsName" 
            placeholder="请输入商品名称" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="秒杀状态">
          <el-select v-model="queryParams.seckillStatus" placeholder="请选择秒杀状态" clearable>
            <el-option label="未开始" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已结束" value="2" />
            <el-option label="已取消" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">创建秒杀</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="seckillList"
      border
      style="width: 100%"
    >
      <el-table-column prop="seckillId" label="ID" width="80" align="center" />
      <el-table-column label="商品信息" min-width="200">
        <template #default="scope">
          <div class="goods-info">
            <el-image 
              v-if="scope.row.goodsImage"
              :src="getImageUrl(scope.row.goodsImage)" 
              style="width: 60px; height: 60px; margin-right: 12px"
              fit="cover"
            />
            <div>
              <div class="goods-name">{{ scope.row.goodsName }}</div>
              <div class="text-gray-500 text-sm">ID: {{ scope.row.goodsId }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="seckillName" label="秒杀名称" min-width="150" />
      <el-table-column label="价格信息" width="150" align="center">
        <template #default="scope">
          <div>
            <div class="original-price">原价: ¥{{ scope.row.originalPrice }}</div>
            <div class="seckill-price">秒杀: ¥{{ scope.row.seckillPrice }}</div>
            <div class="discount-info">
              {{ calculateDiscount(scope.row.originalPrice, scope.row.seckillPrice) }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="库存信息" width="120" align="center">
        <template #default="scope">
          <div>
            <div>总量: {{ scope.row.seckillStock }}</div>
            <div class="text-red-500">已售: {{ scope.row.soldCount }}</div>
            <div class="text-green-500">剩余: {{ scope.row.remainStock }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="limitPerUser" label="限购" width="80" align="center">
        <template #default="scope">
          {{ scope.row.limitPerUser }}件/人
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.seckillStatus)">
            {{ getStatusText(scope.row.seckillStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间信息" width="180">
        <template #default="scope">
          <div class="time-info">
            <div class="text-sm">开始: {{ scope.row.startTime }}</div>
            <div class="text-sm">结束: {{ scope.row.endTime }}</div>
            <div v-if="scope.row.countdown > 0" class="countdown">
              {{ formatCountdown(scope.row.countdown) }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">详情</el-button>
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.seckillStatus === '0'" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '1')"
          >
            开始
          </el-button>
          <el-button 
            v-if="scope.row.seckillStatus === '1'" 
            type="warning" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '2')"
          >
            结束
          </el-button>
          <el-button 
            v-if="['0', '1'].includes(scope.row.seckillStatus)" 
            type="danger" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '3')"
          >
            取消
          </el-button>
          <el-button 
            v-if="scope.row.seckillStatus === '0'" 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 秒杀表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="选择商品" prop="goodsId">
          <el-select 
            v-model="form.goodsId" 
            placeholder="请选择商品"
            @change="handleGoodsChange"
            filterable
          >
            <el-option
              v-for="item in goodsOptions"
              :key="item.goodsId"
              :label="`${item.goodsName} (¥${item.goodsPrice})`"
              :value="item.goodsId"
            >
              <div style="display: flex; align-items: center;">
                <el-image 
                  v-if="item.image"
                  :src="getImageUrl(item.image)" 
                  style="width: 30px; height: 30px; margin-right: 8px"
                  fit="cover"
                />
                <div>
                  <div>{{ item.goodsName }}</div>
                  <div style="font-size: 12px; color: #999;">¥{{ item.goodsPrice }} | 库存: {{ item.sellStatus }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="秒杀名称" prop="seckillName">
          <el-input v-model="form.seckillName" placeholder="请输入秒杀活动名称" />
        </el-form-item>
        
        <el-form-item label="商品原价" prop="originalPrice">
          <el-input-number v-model="form.originalPrice" :min="0" :precision="2" :step="1" />
          <span class="ml-2 text-gray-500">元</span>
        </el-form-item>
        
        <el-form-item label="秒杀价格" prop="seckillPrice">
          <el-input-number v-model="form.seckillPrice" :min="0" :precision="2" :step="1" />
          <span class="ml-2 text-gray-500">元</span>
        </el-form-item>
        
        <el-form-item label="秒杀库存" prop="seckillStock">
          <el-input-number v-model="form.seckillStock" :min="1" :precision="0" />
          <span class="ml-2 text-gray-500">件</span>
        </el-form-item>
        
        <el-form-item label="每人限购" prop="limitPerUser">
          <el-input-number v-model="form.limitPerUser" :min="1" :precision="0" />
          <span class="ml-2 text-gray-500">件</span>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 秒杀详情对话框 -->
    <el-dialog
      title="秒杀详情"
      v-model="detailVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="秒杀ID">{{ detailForm.seckillId }}</el-descriptions-item>
        <el-descriptions-item label="商品ID">{{ detailForm.goodsId }}</el-descriptions-item>
        <el-descriptions-item label="商品名称" :span="2">{{ detailForm.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="秒杀名称" :span="2">{{ detailForm.seckillName }}</el-descriptions-item>
        <el-descriptions-item label="商品原价">¥{{ detailForm.originalPrice }}</el-descriptions-item>
        <el-descriptions-item label="秒杀价格">¥{{ detailForm.seckillPrice }}</el-descriptions-item>
        <el-descriptions-item label="秒杀库存">{{ detailForm.seckillStock }}件</el-descriptions-item>
        <el-descriptions-item label="已售数量">{{ detailForm.soldCount }}件</el-descriptions-item>
        <el-descriptions-item label="剩余库存">{{ detailForm.remainStock }}件</el-descriptions-item>
        <el-descriptions-item label="每人限购">{{ detailForm.limitPerUser }}件</el-descriptions-item>
        <el-descriptions-item label="秒杀状态">
          <el-tag :type="getStatusTagType(detailForm.seckillStatus)">
            {{ getStatusText(detailForm.seckillStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="倒计时">
          {{ detailForm.countdown > 0 ? formatCountdown(detailForm.countdown) : '已结束' }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间" :span="2">{{ detailForm.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间" :span="2">{{ detailForm.endTime }}</el-descriptions-item>
        <el-descriptions-item label="商品图片" :span="2">
          <el-image 
            v-if="detailForm.goodsImage"
            :src="getImageUrl(detailForm.goodsImage)" 
            style="width: 150px; height: 150px"
            :preview-src-list="[getImageUrl(detailForm.goodsImage)]"
            fit="cover"
          />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSeckillPage, 
  getSeckillDetail, 
  createSeckill, 
  updateSeckill,
  deleteSeckill,
  updateSeckillStatus
} from '@/api/seckill'
import { getGoodsList } from '@/api/goods'
import { handlePageResponse } from '@/utils/pagination'

// 秒杀列表
const seckillList = ref([])
// 商品选项
const goodsOptions = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 详情对话框可见状态
const detailVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('创建秒杀')
// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  goodsName: '',
  seckillStatus: ''
})

// 表单数据
const form = reactive({
  seckillId: null,
  goodsId: null,
  seckillName: '',
  originalPrice: 0,
  seckillPrice: 0,
  seckillStock: 0,
  limitPerUser: 1,
  startTime: '',
  endTime: ''
})

// 详情表单
const detailForm = ref({})

// 表单验证规则
const rules = {
  goodsId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  seckillName: [
    { required: true, message: '请输入秒杀名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  originalPrice: [
    { required: true, message: '请输入商品原价', trigger: 'blur' }
  ],
  seckillPrice: [
    { required: true, message: '请输入秒杀价格', trigger: 'blur' }
  ],
  seckillStock: [
    { required: true, message: '请输入秒杀库存', trigger: 'blur' }
  ],
  limitPerUser: [
    { required: true, message: '请输入每人限购数量', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '未开始',
    '1': '进行中',
    '2': '已结束',
    '3': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '0': 'info',
    '1': 'success',
    '2': 'warning',
    '3': 'danger'
  }
  return statusMap[status] || ''
}

// 计算折扣
const calculateDiscount = (original, seckill) => {
  if (!original || !seckill) return ''
  const discount = ((original - seckill) / original * 100).toFixed(1)
  return `${discount}% off`
}

// 格式化倒计时
const formatCountdown = (seconds) => {
  if (seconds <= 0) return '已结束'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchData(),
    fetchGoodsOptions()
  ])
})

// 获取秒杀列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getSeckillPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    seckillList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取秒杀列表失败:', error)
    ElMessage.error('获取秒杀列表失败')
  } finally {
    loading.value = false
  }
}

// 获取商品选项
const fetchGoodsOptions = async () => {
  try {
    const res = await getGoodsList()
    goodsOptions.value = res.data || []
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.goodsName = ''
  queryParams.seckillStatus = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加秒杀
const handleAdd = () => {
  dialogTitle.value = '创建秒杀'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑秒杀
const handleEdit = (row) => {
  dialogTitle.value = '编辑秒杀'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理商品变化
const handleGoodsChange = (goodsId) => {
  const selectedGoods = goodsOptions.value.find(item => item.goodsId === goodsId)
  if (selectedGoods) {
    form.originalPrice = selectedGoods.goodsPrice
    form.seckillName = `${selectedGoods.goodsName}限时秒杀`
  }
}

// 处理查看秒杀详情
const handleView = async (row) => {
  try {
    const res = await getSeckillDetail(row.seckillId)
    if (res.code === 200) {
      detailForm.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取秒杀详情失败:', error)
    ElMessage.error('获取秒杀详情失败')
  }
}

// 处理删除秒杀
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认要删除秒杀"${row.seckillName}"吗？此操作将永久删除该秒杀，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteSeckill(row.seckillId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      fetchData()
    } catch (error) {
      console.error('删除秒杀失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 处理更新秒杀状态
const handleUpdateStatus = (row, status) => {
  const statusText = getStatusText(status)
  ElMessageBox.confirm(
    `确认将秒杀"${row.seckillName}"设为${statusText}状态吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateSeckillStatus(row.seckillId, status)
      ElMessage({
        type: 'success',
        message: `状态更新成功!`
      })
      fetchData()
    } catch (error) {
      console.error('更新秒杀状态失败:', error)
      ElMessage({
        type: 'error',
        message: '状态更新失败'
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  form.seckillId = null
  form.goodsId = null
  form.seckillName = ''
  form.originalPrice = 0
  form.seckillPrice = 0
  form.seckillStock = 0
  form.limitPerUser = 1
  form.startTime = ''
  form.endTime = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    // 验证时间
    if (form.startTime >= form.endTime) {
      ElMessage.error('结束时间必须大于开始时间')
      return
    }
    
    // 验证价格
    if (form.seckillPrice >= form.originalPrice) {
      ElMessage.error('秒杀价格必须小于原价')
      return
    }
    
    submitLoading.value = true
    try {
      if (form.seckillId) {
        await updateSeckill(form)
        ElMessage({
          type: 'success',
          message: '更新成功!'
        })
      } else {
        await createSeckill(form)
        ElMessage({
          type: 'success',
          message: '创建成功!'
        })
      }
      dialogVisible.value = false
      fetchData()
    } catch (error) {
      console.error('保存秒杀失败:', error)
      ElMessage({
        type: 'error',
        message: '保存失败，请稍后再试'
      })
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.goods-info {
  display: flex;
  align-items: center;
}

.goods-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 12px;
}

.seckill-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.discount-info {
  color: #67c23a;
  font-size: 12px;
}

.time-info {
  font-size: 12px;
}

.countdown {
  color: #f56c6c;
  font-weight: bold;
  margin-top: 4px;
}

.text-sm {
  font-size: 14px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-red-500 {
  color: #ef4444;
}

.text-green-500 {
  color: #10b981;
}

.ml-2 {
  margin-left: 8px;
}
</style>

